﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LdtJudge.DataEngine.Common
{
    /// <summary>
    /// http访问帮助类
    /// </summary>
    public class HttpHelp
    {
        /// <summary>
        /// post传值JSON返回Json
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="json">参数</param>
        /// <returns></returns>
        public static string CreatePostHttpResponse(string url, string json)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
            request.Method = "Post";//请求方式
            request.ContentType = "application/json";//链接类型
            byte[] data = System.Text.Encoding.UTF8.GetBytes(json);
            request.ContentLength = data.Length;
            System.IO.Stream sm = request.GetRequestStream();
            sm.Write(data, 0, data.Length);
            sm.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);
            Char[] readBuff = new Char[256];
            int count = streamRead.Read(readBuff, 0, 256);
            String content = "";
            while (count > 0)
            {
                String outputData = new String(readBuff, 0, count);
                content += outputData;
                count = streamRead.Read(readBuff, 0, 256);
            }
            response.Close();
            return content;
        }

        /// <summary>
        /// 进行HTTP请求发送数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpWebResponse CreatePostHttpResponse(string url, Dictionary<string, string> parameters)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
            request.Method = "Get";//请求方式
            request.ContentType = "application/x-www-form-urlencoded";//链接类型
                                                                      //构造查询字符串
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                bool first = true;
                foreach (string key in parameters.Keys)
                {

                    if (!first)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        first = false;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                //写入请求流
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

        #region Base64进行解码编码
        /// <summary>
        /// UTF8形式的编码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string EnDataBase64(object data)
        {
            if(data!=null)
            {
                byte[] bydata = Encoding.GetEncoding(65001).GetBytes(data.ToString());
                return Convert.ToBase64String(bydata);
            }
            return string.Empty;
        }
        /// <summary>
        /// UTF8形式的解码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string DeDataBase64(object data)
        {
            byte[] bydata = ObjectToBytes(data);
            return Convert.ToBase64String(bydata);
        }



        // Base64 解码  
        /// <summary>  
        /// 对Base64编码的字符串进行解码  
        /// </summary>  
        /// <param name="codepage">代码页,utf-8:65001，gb2132:936</param>  
        /// <param name="encode">需要解码的字符串</param>  
        /// <returns></returns>  
        public static string DeCodeBase64new(int codepage, string encode)
        {
            string decode = "";
            try
            {
                byte[] bytes = Convert.FromBase64String(encode);
                decode = Encoding.GetEncoding(codepage).GetString(bytes);
            }
            catch (Exception ex)
            {
                decode = encode;
            }

            return decode;
        }

        #endregion

        #region 对象数据转字节数组
        /// <summary> 
        /// 将一个object对象序列化，返回一个byte[]         
        /// </summary> 
        /// <param name="obj">能序列化的对象</param>         
        /// <returns></returns> 
        public static byte[] ObjectToBytes(object obj)
        {
            string jsonstr = CommonFormat.ReturnJsonString(obj);
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsonstr);
            return byteArray;
        }

        /// <summary> 
        /// 将一个序列化后的byte[]数组还原         
        /// </summary>
        /// <param name="Bytes"></param>         
        /// <returns></returns> 
        public static object BytesToObject<T>(byte[] Bytes)
        {
            string jsonstr = System.Text.Encoding.UTF8.GetString(Bytes);
            T mo = CommonFormat.ReturnJsonToModel<T>(jsonstr);
            return mo;
        }


        #endregion

        #region 进行HTTP请求
        /// <summary>
        /// 发送请求的方法
        /// </summary>
        /// <param name="Url">地址</param>
        /// <param name="postDataStr">数据</param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/json";
            ///将数据写入URL中
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
            myStreamWriter.Write(postDataStr);

            myStreamWriter.Close();

            //获取返回内容
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="codeName">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string EncodeBase64(Encoding encode, string source)
        {
            byte[] bytes = encode.GetBytes(source);
            try
            {
                source = Convert.ToBase64String(bytes);
            }
            catch
            {
                
            }
            return source;
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        {
            return EncodeBase64(Encoding.UTF8, source);
        }

        public static HttpWebRequest webrequest;
        public static HttpWebRequest GetHttpWebRequest(string Url) 
        {
            if (webrequest==null)
            {
                webrequest = (HttpWebRequest)HttpWebRequest.Create(Url);
            }
            else
            {
                webrequest = (HttpWebRequest)HttpWebRequest.Create(Url);
            }
            return webrequest;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPostJson(string Url, string postDataStr, Dictionary<string, string> headers=null)
        {

            //HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(Url);
            GetHttpWebRequest(Url);
            webrequest.Method = "post";
            webrequest.ContentType = "application/json;charset=utf-8";
            webrequest.Timeout = 300000;
            if(headers!=null && headers.Count>0)
            {
                foreach (string key in headers.Keys)
                {
                    if(!string.IsNullOrWhiteSpace(headers[key]))
                    {
                        webrequest.Headers.Add(key, headers[key]);
                    }
                }
            }
            byte[] postdatabyte = Encoding.UTF8.GetBytes(postDataStr);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();
            using (var httpWebResponse = webrequest.GetResponse())
            using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                String ret = responseStream.ReadToEnd();
                string result = ret.ToString();
                return result;
            }

        }

      



        /// <summary>
        /// 获取HTTP数据内容
        /// </summary>
        /// <param name="Url">地址</param>
        /// <param name="postDataStr">参数数据</param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr)
        {                                                                                                                                                                                                                                           
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            dynamic valueList = JsonConvert.DeserializeObject<dynamic>(retString);
            string resutes = "";
            if (valueList.code == "1")
            {
                resutes = valueList.body.content.ToString();
            }
            return resutes;
        }


        public static string HttpGet(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        /// <summary>
        /// POST整个字符串到URL地址中
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="jsonParas"></param>
        /// <returns></returns>
        public static string PostJsonBody1(string Url, string jsonParas)
        {



            string strURL = Url;

            //创建一个HTTP请求 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式 
            request.Method = "POST";
            //内容类型
            //request.ContentType = "application/x-www-form-urlencoded";

            //设置参数，并进行URL编码

            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);  

            byte[] payload;
            //将Json字符串转化为字节 
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength  
            request.ContentLength = payload.Length;
            //发送请求，获得请求流

            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流

            //String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream s = response.GetResponseStream();

            //Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            return postContent;//返回Json数据
        }


        public static string PostJsonBody(string url, string body)
        {
            string formUrl = url;
            //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
            byte[] postData = System.Text.Encoding.UTF8.GetBytes(formUrl);
            byte[] postData2 = System.Text.Encoding.UTF8.GetBytes(body);
            // 设置提交的相关参数 
            System.Net.HttpWebRequest request = System.Net.WebRequest.Create(formUrl) as System.Net.HttpWebRequest;
            System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
            request.Method = "POST";
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;
            request.ContentType = "application/json";
            //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            //request.ContentLength = postData.Length;

            Stream outstream = null;
            outstream = request.GetRequestStream();

            //自定义body内容postData2
            outstream.Write(postData2, 0, postData2.Length);

            // 提交请求数据 
            System.IO.Stream outputStream = request.GetRequestStream();
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();

            System.Net.HttpWebResponse response;
            System.IO.Stream responseStream;
            System.IO.StreamReader reader;
            string srcString;
            response = request.GetResponse() as System.Net.HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("UTF-8"));
            srcString = reader.ReadToEnd();
            string result = srcString;   //返回值赋值
            reader.Close();
            return result;
        }
        #endregion
    }
}
